import { defineStore } from "pinia";

import { login, logout, getInfo } from "@/api/login";
import { getToken, setToken, removeToken } from "@/utils/auth";
import defAva from "@/assets/images/profile.jpg";
import { encrypt } from "@/utils/jsencrypt";

const useUserStore = defineStore("user", {
  state: () => ({
    token: getToken(),
    id: "",
    name: "",
    avatar: "",
    roles: [],
    permissions: [],
  }),
  actions: {
    // 登录
    login(userInfo: any) {
      const loginId = userInfo.loginId.trim();
      const loginPwd = encrypt(userInfo.loginPwd);
      const code = userInfo.code;
      const uuid = userInfo.uuid;
      return new Promise<void>((resolve, reject) => {
        login(loginId, loginPwd, code, uuid)
          .then(({ data }) => {
            setToken(data.token);
            this.token = data.token;
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 获取用户信息
    async getInfo() {
      const resp = await getInfo();
      const user = resp.data.user;
      const roles = resp.data.roles;

      const avatar = user.avatar == "" || user.avatar == null ? defAva : user.avatar;

      if (roles && roles.length > 0) {
        // 验证返回的roles是否是一个非空数组
        this.roles = roles;
        this.permissions = resp.permissions;
      } else {
        this.roles = ["ROLE_DEFAULT"] as any;
      }

      this.id = user.userId;
      this.name = user.loginId;
      this.avatar = avatar;
    },
    // 退出系统
    async logOut() {
      await logout();
      this.token = "";
      this.roles = [];
      this.permissions = [];
      removeToken();
    },
  },
});

export default useUserStore;
